import React, { useState } from 'react';
import { Button, Checkbox, Form, Input, message, Modal, Select, Spin, Tree } from 'antd';
import Tooltip from 'antd/es/tooltip';
import { cloneDeep, debounce } from 'lodash';
import { AutoSizer, List } from 'react-virtualized';

import {
  CloseOutlined,
  PlusCircleOutlined,
  RightOutlined,
  SearchOutlined,
} from '#/utils/antdIcons.js';
import { HttpCode } from '#/utils/contacts.js';
import TRNotification from '#/utils/notification.js';
import planIcon from '@/assets/img/plan_icon.png';
import { iconEmail, iconPhone } from '@/assets/icon/index.js';
import { TRDefault } from '@/components/index.js';

import type { ICreatorOption, IGroupOptions, ISearchFormData } from '../../type';
import { GROUP_OPTION_TYPE, PERSON_OPTIONS_STATUS, PERSON_STATUS } from '../../dictionary';
import { getCreatorResultData } from '../../tool';
import { editUserGroupH, getTianJiUserServerH } from '../../service';
import styles from './index.less';

interface IProps {
  /**
   * 搜索条件
   */
  onPress: (data: Record<string, any>) => void;
  /**
   * searchFormData
   */
  searchFormData: ISearchFormData;
  /**
   * 表单值
   */
  value: any;
  /**
   * 刷新基础数据
   */
  getSearchFormData: () => void;
}

const PersonComponent = (props: IProps) => {
  let deepLv = 1; // 最深叶子等级
  const [form] = Form.useForm();
  const ref = React.useRef<any>();
  const { onPress, value = [], searchFormData, getSearchFormData } = props;
  const { dealElementOptions, dealElementModalOptions, creatorOptionsObj } = searchFormData;
  const [visible, setVisible] = useState<boolean>(true);
  const [status, setStatus] = useState<PERSON_STATUS>(PERSON_STATUS.SELECT);
  const [activeKey, setActiveKey] = useState<PERSON_OPTIONS_STATUS>(
    PERSON_OPTIONS_STATUS.GROUP_NAME,
  );
  const [groupOptions, setGroupOptions] = useState<any>();
  // const [checkedList, setCheckedList] = useState<number[]>([]);
  const [checkedData, setCheckedData] = useState<ICreatorOption[]>([]);
  const [showOptions, setShowOptions] = useState<ICreatorOption[]>([]);
  const [originOptions, setOriginOptions] = useState<ICreatorOption[]>([]);
  const [noramlOriginOptions, setNoramlOriginOptions] = useState<ICreatorOption[]>([]);
  const [groupOptionType, setGroupOptionType] = useState<GROUP_OPTION_TYPE>();
  const [groupInfo, setGroupInfo] = useState<IGroupOptions>({});
  const [personSearch, setPersonSearch] = useState<string>();
  const [loading, setLoading] = useState<boolean>(false);
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [creatorOptions, setCreatorOptions] = useState<any[]>([]);

  /* 结算单元 */
  const [searchValue, setSearchValue] = useState<string>('');
  const [checkedStationKeys, setCheckStationKeys] = useState<any>([]);
  const [expandedKeys, setExpandedKeys] = useState([]);
  const [autoExpandParent, setautoExpandParent] = useState(false);
  const [leftNodes, setLeftNodes] = useState<any>([]);
  const [allCheck, setAllCheck] = useState<any>({});
  const [checkedNodes, setcheckedNodes] = useState<any>([]);
  const [treeDataMap, setTreeDataMap] = useState<any>([]);
  const [tradeInputValue, seTradeInputValue] = useState<any>('');

  // 根据传入的value值组装数据
  const getOriginOptions = (list: ICreatorOption[], arr: number[], checked: boolean) => {
    let _arr: any = [];
    if (arr.length > 0) {
      list.forEach((item: ICreatorOption) => {
        let obj = item;
        arr.forEach((i) => {
          if (item.value === i) {
            obj = { ...item, checked };
          }
        });
        _arr = [..._arr, obj];
      });
      return _arr;
    } else {
      return list;
    }
  };

  const initCheckKeys = (tree: any = [], list: any, parentKey = null, lv = 1) => {
    if (lv > deepLv) deepLv = lv;
    for (let i = 0; i < tree.length; i++) {
      const node: any = tree[i];
      const { key, title } = node;
      node.lv = lv;
      node.parentKey = parentKey;
      list.push({
        key,
        title,
        parentKey,
        lv,
      });
      if (node.children) {
        initCheckKeys(node.children, list, node.key, lv + 1);
      }
    }
    return list;
  };

  const initCheckData = () => {
    const _treeDataMap = initCheckKeys(dealElementModalOptions, [], null, 1);
    setTreeDataMap(_treeDataMap);
    const _leafNodes = _treeDataMap.filter((x: any) => x.lv === deepLv);
    setLeftNodes(_leafNodes);
  };

  // 自由选择人员状态 PERSON_STATUS === PERSON_STATUS.SELECT

  // 获取搜索数据
  const getSearchData = (keyWord: string, arr: ICreatorOption[]) => {
    const list: ICreatorOption[] = arr.filter((item: ICreatorOption) => {
      return (
        (item?.email && item?.email?.indexOf(keyWord) !== -1) ||
        (item?.mobile && item?.mobile?.indexOf(keyWord) !== -1) ||
        (item?.name && item?.name?.indexOf(keyWord) !== -1)
      );
    });
    return list;
  };

  // 搜索
  const _onSearchUser = debounce((e: any) => {
    const keyWord = e.target.value;
    const _showOptions = getSearchData(keyWord, originOptions);
    // const _checkedList =
    //   _showOptions?.filter((item) => item.checked)?.map((item) => item.value) || [];
    setShowOptions(_showOptions);
    // setCheckedList(_checkedList);
    setPersonSearch(keyWord);
  }, 300);

  // 选择交易单元
  const onCheckFn = (val: any) => {
    const _checkedNodes = leftNodes.filter((x: any) => val.includes(x.key));
    const checkedKeys = _checkedNodes.map((x: any) => x.key);
    const checkAll = !!checkedKeys.length && checkedKeys.length === leftNodes.length;
    const indeterminate = !!checkedKeys.length && checkedKeys.length < leftNodes.length;
    setAllCheck({
      checkAll,
      indeterminate,
    });
    setcheckedNodes(_checkedNodes);
    setCheckStationKeys(checkedKeys);
    form && form.setFieldsValue({ stationList: checkedKeys });
  };

  // 新增、编辑人员组
  const onGroupOption = (type: GROUP_OPTION_TYPE, data: IGroupOptions = {}) => {
    const _checkedList: number[] = data?.userList?.map((item) => item.userId) || [];
    const arr = getOriginOptions(creatorOptions, _checkedList, true);
    setCheckedData(data?.userList || []);
    setOriginOptions(arr);
    setShowOptions(arr);
    // setCheckedList(_checkedList);
    setNoramlOriginOptions(originOptions);
    setStatus(PERSON_STATUS.EDIT);
    setActiveKey(PERSON_OPTIONS_STATUS.GROUP_NAME);
    setGroupOptionType(type);
    setGroupInfo(data);
    setPersonSearch('');
    const stationIdList = data?.stationIdList?.map((item) => String(item)) || [];
    onCheckFn(stationIdList);
    form &&
      form.setFieldsValue({
        groupName: data?.groupName ? data?.groupName : '',
        stationList: stationIdList,
        userList: _checkedList,
      });
  };

  // 选择人员组
  const onSelectGroup = (item: IGroupOptions) => {
    const { userList = [] } = item;
    let _checkedList = userList.map((a) => a.userId);
    const _originOptions: ICreatorOption[] = getOriginOptions(originOptions, _checkedList, true);
    let list: ICreatorOption[] = [];
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    const _checkedData: ICreatorOption[] = _originOptions.filter((b) => b?.checked) || [];
    _checkedList = list.filter((c) => c?.checked)?.map((d: ICreatorOption) => d.value) || [];
    setCheckedData(_checkedData);
    setOriginOptions(_originOptions);
    setShowOptions(list);
    // setCheckedList(_checkedList);
  };

  // 获取人员组数据
  const getGroup = async () => {
    setLoading(true);
    let res: any = {};
    res = await getTianJiUserServerH();
    if (res && res.statusCode === HttpCode.SUCCESS) {
      const creatorResultData: any = getCreatorResultData(res.data || []);
      const userList = res?.data?.userList?.map((i: any) => ({ ...i, value: i.userId })) || [];
      setCreatorOptions(userList);
      setGroupOptions(creatorResultData.groupOptions || []);
    }
    setLoading(false);
  };

  // 删除人员组
  const deleteGroup = async (item: IGroupOptions) => {
    setLoading(true);
    const res = await editUserGroupH({
      ...item,
      operationType: GROUP_OPTION_TYPE.DEL,
    });
    if (res && res.statusCode === HttpCode.SUCCESS) {
      message.info('删除成功！');
    } else {
      message.info(res?.message || '删除失败！');
    }
    getSearchFormData();
    getGroup();
  };

  // 选择
  const _onChange = (e: any) => {
    const _checked = e.target.checked;
    const _value = e.target.value;
    let list: ICreatorOption[] = [];
    const _originOptions = originOptions.map((item) => {
      if (item.value === _value) {
        return { ...item, checked: _checked };
      } else {
        return item;
      }
    });
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    // const _checkedList: number[] =
    //   list.filter((item) => item?.checked)?.map((item) => item.value) || [];
    const _checkedData: ICreatorOption[] = _originOptions.filter((item) => item?.checked) || [];
    setShowOptions(list);
    setOriginOptions(_originOptions);
    // setCheckedList(_checkedList);
    setCheckedData(_checkedData);
    if (status === PERSON_STATUS.EDIT) {
      form && form.setFieldsValue({ userList: _checkedData.map((item) => item.value) });
    }
  };

  // 清空
  const handelClearOut = () => {
    const _checkedList = checkedData.map((item: ICreatorOption) => item.value);
    const _originOptions = getOriginOptions(originOptions, _checkedList, false);
    let list: ICreatorOption[] = [];
    if (personSearch) {
      list = getSearchData(personSearch, _originOptions);
    } else {
      list = _originOptions;
    }
    setShowOptions(list);
    setOriginOptions(_originOptions);
    // setCheckedList([]);
    setCheckedData([]);
  };

  // 删除已选数据
  const handleDeleteCheckedData = (data: ICreatorOption) => {
    _onChange({ target: { checked: false, value: data.value } });
  };

  // 编辑人员组 PERSON_STATUS === PERSON_STATUS.edit

  // 判断搜索的是不是中文
  const _isChinese = (s: any) => {
    // 中文全匹配
    let ret = true;
    for (let i = 0; i < s.length; i++) ret = ret && s.charCodeAt(i) >= 10000;
    return ret;
  };
  checkedNodes;
  // 搜索交易单元
  const _onSearch = (e: any) => {
    let _expandedKeys = [];
    if (e?.target?.value && _isChinese(e?.target?.value)) {
      _expandedKeys = treeDataMap
        .map((x: any) => (x.title.indexOf(e?.target?.value) > -1 ? x.parentKey : null))
        .filter((item: any, i: any, self: any) => item && self.indexOf(item) === i);
    }
    if (_expandedKeys?.[0]) {
      ref.current.scrollTo({ key: _expandedKeys?.[0], align: 'top' });
    } else {
      ref.current.scrollTo({ key: 0, align: 'top' });
    }
    setExpandedKeys(_expandedKeys);
    setSearchValue(e?.target?.value);
    setautoExpandParent(true);
    seTradeInputValue(e.target.value);
  };

  // 交易单元数据处理
  const loop: any = (data = []) => {
    return data.map((item: any) => {
      const { lv, parentKey, key } = item;
      const index = item.title.indexOf(searchValue);
      const beforeStr = item.title.substr(0, index);
      const afterStr = item.title.substr(index + searchValue.length);
      const _title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className={styles.search_act}>{searchValue}</span>
            {afterStr}
          </span>
        ) : (
          <span>{item.title}</span>
        );
      if (item.children) {
        return { key, title: _title, lv, parentKey, children: loop(item.children) };
      }

      return { key, title: _title, lv, parentKey };
    });
  };

  // 交易单元全选
  const _onChangeAll = (e: any) => {
    const checkAll = e.target.checked;
    const _checkedNodes = checkAll ? [...leftNodes] : [];
    const _checkedKeys: any = _checkedNodes.map((x) => x.key);
    setAllCheck({
      checkAll,
      indeterminate: false,
    });
    setcheckedNodes(_checkedNodes);
    setCheckStationKeys(_checkedKeys);
    form && form.setFieldsValue({ stationList: _checkedKeys });
  };

  const onExpandFn = (_expandedKeys: any) => {
    setExpandedKeys(_expandedKeys);
    setautoExpandParent(false);
  };

  // 清除交易单元
  const _onClearAll = () => {
    setAllCheck({
      checkAll: false,
      indeterminate: false,
    });
    setCheckStationKeys([]);
    setcheckedNodes([]);
    setExpandedKeys([]);
    form && form.setFieldsValue({ stationList: [] });
  };

  // 交易单元排序
  const orderSort = (obj1: any, obj2: any) => {
    const a = obj1.title;
    const b = obj2.title;
    if (b > a) {
      return -1;
    } else if (b < a) {
      return 1;
    } else {
      return 0;
    }
  };

  // 删除某个交易单元
  const _onRemove = (idx: any) => {
    let checkedKeys: any = cloneDeep(checkedStationKeys);
    const checkedNodesResult: any = cloneDeep(checkedNodes);
    checkedNodesResult.splice(idx, 1);
    checkedKeys = checkedNodesResult.map((x: any) => x.key);
    const checkAll = !!checkedKeys.length && checkedKeys.length === leftNodes.length;
    const indeterminate = !!checkedKeys.length && checkedKeys.length < leftNodes.length;
    setAllCheck({
      checkAll,
      indeterminate,
    });
    setcheckedNodes(checkedNodesResult);
    setCheckStationKeys(checkedKeys);
    form && form.setFieldsValue({ stationList: checkedKeys });
  };

  const handleData = () => {
    setPersonSearch('');
    const _checkedData = noramlOriginOptions.filter((item) => item.checked) || [];
    // const _checkedList = _checkedData.map((item) => item.value);
    setCheckedData(_checkedData);
    // setCheckedList(_checkedList);
    setShowOptions(noramlOriginOptions);
    setOriginOptions(noramlOriginOptions);
  };

  // 确定按钮
  const _onOk = async () => {
    if (status === PERSON_STATUS.SELECT) {
      onPress({
        index: 1,
        reminderList: checkedData?.map((item) => item.value),
        reminderData: checkedData,
      });
      setVisible(false);
    } else {
      form &&
        form.validateFields().then(async (values) => {
          setIsLoading(true);
          const params =
            groupOptionType === GROUP_OPTION_TYPE.UPDATE
              ? {
                  groupId: groupInfo?.groupId,
                  ...values,
                  stationIdList: values.stationList,
                  userIdList: values.userList,
                  operationType: groupOptionType,
                }
              : {
                  ...values,
                  stationIdList: values.stationList,
                  userIdList: values.userList,
                  operationType: groupOptionType,
                };
          const res = await editUserGroupH({
            ...params,
          });
          if (res && res.statusCode === HttpCode.SUCCESS) {
            getSearchFormData();
            getGroup();
            message.info('保存成功！');
            handleData();
            setStatus(PERSON_STATUS.SELECT);
          } else {
            message.info(res?.message || '保存失败！');
          }
          setIsLoading(false);
        });
    }
  };

  // 取消按钮
  const _onCancel = () => {
    if (status === PERSON_STATUS.SELECT) {
      setVisible(false);
      onPress({ index: 0 });
    } else {
      handleData();
      setStatus(PERSON_STATUS.SELECT);
    }
  };

  React.useEffect(() => {
    initCheckData();
    getGroup();
  }, []);

  React.useEffect(() => {
    // setCheckedList(value);
    const _showOptions = getOriginOptions(creatorOptions, value, true);
    setShowOptions(_showOptions);
    setOriginOptions(_showOptions);
    const _checkedData =
      creatorOptions
        ?.filter((i) => value?.includes(i.userId))
        .map((i) => ({ ...i, checked: true })) || [];
    setCheckedData(_checkedData);
  }, [value, creatorOptions]);

  // 人员组列表组件
  const groupItemRender = ({ key, index, style }: any) => {
    const item: IGroupOptions = groupOptions[index] || {};
    return (
      <div className={styles.group} key={key} style={style}>
        <div className={styles.groupName} onClick={() => onSelectGroup(item)}>
          <Tooltip title={item?.label} placement="topLeft">
            {item?.label}
          </Tooltip>
        </div>
        <div className={styles.options}>
          <div
            className={styles.edit}
            onClick={() => onGroupOption(GROUP_OPTION_TYPE.UPDATE, item)}
          >
            {' '}
            编辑
          </div>
          <div className={styles.edit} onClick={() => deleteGroup(item)}>
            {' '}
            删除
          </div>
        </div>
      </div>
    );
  };

  // 人员选择列表组件
  const leftItemRender = ({ key, index, style }: any) => {
    const item: ICreatorOption = showOptions[index];
    return (
      <div className={styles.item} key={key} style={style}>
        <Checkbox
          value={item.value}
          checked={item.checked}
          className={styles.checkBox}
          onChange={_onChange}
        >
          {item.name}
        </Checkbox>
        <div className={styles.info}>
          <div className={styles.mobile}>
            <img src={iconPhone} className={styles.logo} />
            {item.mobile || '暂无'}
          </div>
          <div className={styles.email}>
            <img src={iconEmail} className={styles.logo} />
            {item.email || '暂无'}
          </div>
        </div>
      </div>
    );
  };

  // 已选择人员列表组件
  const rightItemRender = ({ key, index, style }: any) => {
    const item: ICreatorOption = checkedData[index];
    return (
      <div className={styles.item} key={key} style={style}>
        <div className={styles.name}>
          <div>{item?.name || ''}</div>
          <CloseOutlined
            className={styles.close}
            onClick={() => {
              handleDeleteCheckedData(item);
            }}
          />
        </div>
        <div className={styles.info}>
          <div className={styles.mobile}>
            <img src={iconPhone} className={styles.logo} />
            {item.mobile || '暂无'}
          </div>
          <div className={styles.email}>
            <img src={iconEmail} className={styles.logo} />
            {item.email || '暂无'}
          </div>
        </div>
      </div>
    );
  };

  // 人员选择组件
  const userRender = () => {
    return (
      <>
        <div className={styles.center}>
          <Input
            placeholder="搜索"
            suffix={<SearchOutlined />}
            allowClear
            onChange={_onSearchUser}
          />
          <div className={styles.centerBottom}>
            {!showOptions?.length ? (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            ) : (
              <AutoSizer>
                {({ height, width }: any) => (
                  <div className={styles.checkboxGroup}>
                    <List
                      height={height}
                      width={width}
                      rowCount={showOptions?.length || 0}
                      rowHeight={80}
                      rowRenderer={leftItemRender}
                      key="userId"
                    />
                  </div>
                )}
              </AutoSizer>
            )}
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.rightTop}>
            <div>已选{checkedData?.length || 0}项</div>
            <div onClick={handelClearOut} className={styles.clear}>
              清空
            </div>
          </div>
          <div className={styles.content}>
            {!checkedData?.length ? (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            ) : (
              <AutoSizer>
                {({ height, width }: any) => (
                  <List
                    height={height}
                    rowCount={checkedData?.length || 0}
                    rowHeight={80}
                    rowRenderer={rightItemRender}
                    width={width}
                    key="userId"
                  />
                )}
              </AutoSizer>
            )}
          </div>
        </div>
      </>
    );
  };

  // 交易单元组件
  const stationRender = () => {
    return (
      <>
        <div className={styles.center}>
          <div className={styles.centerTop}>
            <Input
              placeholder="搜索"
              suffix={<SearchOutlined />}
              allowClear
              value={tradeInputValue}
              onChange={_onSearch}
            />
          </div>
          <div className={styles.centerBottom}>
            <div className={styles.mainBox}>
              <div>
                <Checkbox
                  checked={allCheck?.checkAll || false}
                  indeterminate={allCheck?.indeterminate || false}
                  onChange={_onChangeAll}
                >
                  全选
                </Checkbox>
              </div>
              <div className={styles.treeBox}>
                <Tree
                  ref={ref}
                  blockNode={true}
                  checkable={true}
                  treeData={loop(dealElementModalOptions || [])}
                  checkedKeys={checkedStationKeys}
                  autoExpandParent={autoExpandParent}
                  expandedKeys={expandedKeys}
                  onExpand={onExpandFn}
                  onCheck={onCheckFn}
                  height={300}
                />
              </div>
            </div>
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.choosebox}>
            <div className={styles.box_header}>
              <div>{`已选${checkedNodes.length}项`}</div>
              <div className={styles.clear} onClick={_onClearAll}>
                清空
              </div>
            </div>
            <div className={styles.box_content}>
              <ul className={styles.chooseList}>
                {checkedNodes.sort(orderSort).map((item: any, idx: number) => {
                  return (
                    <li key={item?.key || ''}>
                      <div className={styles.chooseName}>{item?.title || ''}</div>
                      <CloseOutlined className={styles.close} onClick={() => _onRemove(idx)} />
                    </li>
                  );
                })}
              </ul>
            </div>
          </div>
        </div>
      </>
    );
  };

  // 人员组名组件
  const groupRender = () => {
    return (
      <>
        <div className={styles.center} />
        <div className={styles.right} />
      </>
    );
  };

  // 编辑人员组对应右边组件渲染
  const rightRender = () => {
    if (activeKey === PERSON_OPTIONS_STATUS.USER) {
      return userRender();
    } else if (activeKey === PERSON_OPTIONS_STATUS.STATION) {
      return stationRender();
    } else if (activeKey === PERSON_OPTIONS_STATUS.GROUP_NAME) {
      return groupRender();
    }
  };

  // 自由选择人员组件
  const renderNoraml = () => {
    return (
      <div className={styles.noraml}>
        <div className={styles.left}>
          <div className={styles.leftTop}>
            <div>人员组</div>
            <div className={styles.button} onClick={() => onGroupOption(GROUP_OPTION_TYPE.ADD, {})}>
              <PlusCircleOutlined className={styles.logo} />
              新建
            </div>
          </div>
          <div className={styles.leftCenter}>
            {loading ? (
              <Spin spinning={loading} />
            ) : (
              <AutoSizer>
                {({ height, width }: any) => (
                  <List
                    height={height}
                    rowCount={groupOptions?.length || 0}
                    rowHeight={35} //高度是item-name的css高度
                    rowRenderer={groupItemRender}
                    width={width}
                    key="groupId"
                  />
                )}
              </AutoSizer>
            )}
          </div>
        </div>
        <div className={styles.center}>
          <Input
            placeholder="搜索"
            suffix={<SearchOutlined />}
            allowClear
            onChange={_onSearchUser}
          />
          <div className={styles.centerBottom}>
            <div className={styles.allUser}>所有人</div>
            {!showOptions?.length ? (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            ) : (
              <AutoSizer>
                {({ height, width }: any) => (
                  <div className={styles.checkboxGroup}>
                    <List
                      height={height}
                      width={width}
                      rowCount={showOptions?.length || 0}
                      rowHeight={80}
                      rowRenderer={leftItemRender}
                      key="userId"
                    />
                  </div>
                )}
              </AutoSizer>
            )}
          </div>
        </div>
        <div className={styles.right}>
          <div className={styles.rightTop}>
            <div>已选{checkedData?.length || 0}项</div>
            <div onClick={handelClearOut} className={styles.clear}>
              清空
            </div>
          </div>
          <div className={styles.content}>
            {!checkedData?.length ? (
              <TRDefault type={'emptysm'} message={'暂无数据'} />
            ) : (
              <AutoSizer>
                {({ height, width }: any) => (
                  <List
                    height={height}
                    rowCount={checkedData?.length || 0}
                    rowHeight={80}
                    rowRenderer={rightItemRender}
                    width={width}
                    key="userId"
                  />
                )}
              </AutoSizer>
            )}
          </div>
        </div>
      </div>
    );
  };

  // 分组编辑组件
  const renderEdit = () => {
    return (
      <div className={styles.edit}>
        <div className={styles.left}>
          <Form
            className={styles.form}
            form={form}
            name="todo"
            colon={false}
            labelAlign="left"
            autoComplete="off"
            requiredMark={false}
          >
            <Form.Item
              name="groupName"
              label="组名"
              rules={[{ required: true, message: '请填写组名' }]}
            >
              <Input
                maxLength={50}
                placeholder="请输入"
                onClick={() => {
                  setActiveKey(PERSON_OPTIONS_STATUS.GROUP_NAME);
                }}
              />
            </Form.Item>
            <Form.Item
              name="stationList"
              label="交易单元"
              rules={[{ required: true, message: '请选择交易单元' }]}
            >
              <Select
                placeholder={'请选择'}
                suffixIcon={<RightOutlined />}
                showArrow={true}
                open={false}
                onClick={() => {
                  setActiveKey(PERSON_OPTIONS_STATUS.STATION);
                }}
                mode="multiple"
                maxTagTextLength={1}
                maxTagCount={1}
                options={dealElementOptions as any[]}
              />
            </Form.Item>
            <Form.Item
              name="userList"
              label="人员选择"
              rules={[{ required: true, message: '请选择人员' }]}
            >
              <Select
                placeholder={'请选择'}
                suffixIcon={<RightOutlined />}
                showArrow={true}
                open={false}
                onClick={() => {
                  setActiveKey(PERSON_OPTIONS_STATUS.USER);
                }}
                mode="multiple"
                maxTagTextLength={1}
                maxTagCount={1}
                options={creatorOptions as any[]}
              />
            </Form.Item>
          </Form>
        </div>
        {rightRender()}
      </div>
    );
  };

  // 渲染主体
  const renderMain = () => {
    if (status === PERSON_STATUS.SELECT) {
      return renderNoraml(); //自由选择人员
    } else if (status === PERSON_STATUS.EDIT) {
      return renderEdit(); // 新增编辑分组
    }
  };

  const footerRender = () => [
    <Button key="dtest1" onClick={_onCancel} loading={isLoading}>
      取消
    </Button>,
    <Button key="dtest2" type="primary" onClick={_onOk} loading={isLoading}>
      提交
    </Button>,
  ];

  return (
    <Modal
      width={826}
      className={styles.modal}
      centered
      maskClosable={false}
      visible={visible}
      title={
        <div className={styles.titleDiv}>
          <img src={planIcon} className={styles.titleLogo} />
          <span className={styles.title}>
            {status === PERSON_STATUS.SELECT
              ? '自由选择人员'
              : groupOptionType === GROUP_OPTION_TYPE.ADD
              ? '分组新建'
              : '分组编辑'}
          </span>
        </div>
      }
      onCancel={_onCancel}
      footer={footerRender()}
    >
      <div className={styles.container}>{renderMain()}</div>
    </Modal>
  );
};

class PersonModal {
  __key__ = '';

  show = (props: any) => {
    return new Promise((resolve) => {
      if (this.__key__ !== '') return;
      this.__key__ = String(Date.now());
      TRNotification.add({
        key: this.__key__,
        content: (
          <PersonComponent
            {...props}
            onPress={(result: any) => {
              TRNotification.remove(this.__key__);
              this.__key__ = '';
              resolve(result);
            }}
          />
        ),
        duration: null,
        dismiss: this.dismiss,
      });
    });
  };

  dismiss = () => {
    if (this.__key__.length > 0) {
      TRNotification.remove(this.__key__);
      this.__key__ = '';
    }
  };
}

export default new PersonModal();
